package com.py.credit.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.AreaName;
import com.py.credit.entity.AreaRelationEntity;
import com.py.credit.entity.CollectionForm;
import com.py.credit.entity.Dept;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.TableResult;
import com.py.credit.service.AreaDeptService;
import com.py.credit.service.CollectionFormService;
import com.py.credit.service.ContentService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.framework.core.entity.SysAreaEntity;
import com.py.framework.core.entity.SysOfficeEntity;
import com.py.framework.core.helper.HttpServletHelper;

@Controller
@RequestMapping(value = "/collectionForm")
public class CollectionFormController {
	
	@Autowired
	private CollectionFormService collectionFormService;

	@Autowired
	private RemoteBaseService remoteBaseService;
	
	@Autowired
	private ContentService contentService;
	@Autowired
	private AreaDeptService areaDeptService;

	/**
	 * @api {get} /collectionForm/list.json 部门信用数据统计（只统计正确的数据） 页面刷新展示数据
	 * @apiName getList
	 * @apiVersion 0.0.1
	 * @apiGroup 归集表单
	 * 
	 * @apiParam {String} regionCode 地区编码(选填)
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *  {"code":0,"msg":null,"count":0,"data":{"totalNum":{"num":0,"deptNum":0},"deptNum":[]}}  
	 */
	@ResponseBody
	@RequestMapping(value = "/list.json")
	public RestServiceResult<Map<String, Object>> getList(
			@RequestParam(defaultValue = "", required = true, value = "regionCode") String regionCode,
			HttpServletRequest request) {
		RestServiceResult<Map<String, Object>> r = new RestServiceResult<>();
		Map<String, Object> result = new HashMap<String, Object>();
		Map<Long, String> deptInfo = new HashMap<Long, String>();
		RestServiceResult<List<SysOfficeEntity>> office = null;
		RestServiceResult<Map<String, Object>> resultInfo = new RestServiceResult<Map<String, Object>>();
		RestServiceResult<List<SysAreaEntity>> allAreaInfo = null;
		String token = HttpServletHelper.getUserToken(request);
		// 获取所有区域信息
		// 有区域ID，调用获取该区域及其下级区域的信息
		allAreaInfo = remoteBaseService.getAllAreas(regionCode, token);
		if (null != allAreaInfo && RestServiceResult.CODE_SUCCESS != allAreaInfo.getCode()) {
			r.setCode(allAreaInfo.getCode());
			r.setMsg(allAreaInfo.getMsg());
			return r;
		}
		// 通过区域ID获取部门信息,区域ID为空，获取所有部门信息
		office = remoteBaseService.getOfficesByAreaId(regionCode, token);
		if (null != office && RestServiceResult.CODE_SUCCESS != office.getCode()) {
			r.setCode(office.getCode());
			r.setMsg(office.getMsg());
			return r;
		}
		if (!CollectionUtils.isEmpty(office.getData())) {
			for (SysOfficeEntity entity : office.getData()) {
				deptInfo.put(entity.getId(), entity.getOfficeName());
			}
		} else {
			return resultInfo;
		}
		result = collectionFormService.getDeptNum(allAreaInfo, deptInfo, office.getData());
		r.setData(result);
		return r;
	}
	
	/**
	 * @api {get} /collectionForm/detail.json 单个部门信用数据统计
	 * @apiName getDataforDeptId
	 * @apiVersion 0.0.1
	 * @apiGroup 归集表单
	 * 
	 * @apiParam {String} deptId 部门id(必填)
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *  {"code":0,"msg":null,"count":0,"data":[{"deptId":0,"sjnum":0,"xynum":0,"num":100,"deptName":null,"tableName":"餐饮协会公司信息","creditTime":"2018-03-29"},{"deptId":0,"sjnum":0,"xynum":0,"num":100,"deptName":null,"tableName":"餐饮协会清算信息","creditTime":"2018-03-29"}]}
	 */
	@ResponseBody
	@RequestMapping(value = "/detail.json")
	public RestServiceResult<List<CollectionForm>> getDataforDeptId(
			@RequestParam(defaultValue = "", required = true, value = "deptId") String deptId) {

		List<CollectionForm> list = collectionFormService.getDataForDeptId(deptId);

		return new RestServiceResult<List<CollectionForm>>(list);
	}
	
	/**
	 * @api {get} /collectionForm/downData.json 单个区域信用数据下载表格
	 * @apiName downDataforDeptId
	 * @apiVersion 0.0.1
	 * @apiGroup 归集表单下载
	 * 
	 * @apiParam {String} regionCode 区域id(必填)
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *  
	 */
	@ResponseBody
	@RequestMapping(value = "/downData.json")
	public RestServiceResult<Object> downDataforDeptId(
			@RequestParam(defaultValue = "", required = true, value = "regionCode") String regionCode,
			HttpServletResponse response, HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<Long, String> deptInfo = new HashMap<Long, String>();
		RestServiceResult<List<SysOfficeEntity>> office = null;
		RestServiceResult<Map<String, Object>> resultInfo = new RestServiceResult<Map<String, Object>>();
		RestServiceResult<List<SysAreaEntity>> allAreaInfo = null;
		Map<Integer,List<CollectionForm>> colMap=new HashMap<Integer,List<CollectionForm>>();
		Map<Integer,String> areaMap=new HashMap<Integer,String>();
		AreaName area=null;
		RestServiceResult<Object> result2 = new RestServiceResult<Object>();
		List<CollectionForm> collist=new ArrayList<CollectionForm>();
		String token = HttpServletHelper.getUserToken(request);
		// 获取所有区域信息
		// 有区域ID，调用获取该区域及其下级区域的信息
		allAreaInfo = remoteBaseService.getAllAreas(regionCode, token);
		if (null != allAreaInfo && RestServiceResult.CODE_SUCCESS != allAreaInfo.getCode()) {
			result2.setCode(allAreaInfo.getCode());
			result2.setMsg(allAreaInfo.getMsg());
			
		}
		// 通过区域ID获取部门信息,区域ID为空，获取所有部门信息
		office = remoteBaseService.getOfficesByAreaId(regionCode, token);
		if (null != office && RestServiceResult.CODE_SUCCESS != office.getCode()) {
			result2.setCode(office.getCode());
			result2.setMsg(office.getMsg());
			
		}
		if (!CollectionUtils.isEmpty(office.getData())) {
			for (SysOfficeEntity entity : office.getData()) {
				deptInfo.put(entity.getId(), entity.getOfficeName());
			}
		} else {
			return result2;
		}
		result = collectionFormService.getDeptNum(allAreaInfo, deptInfo, office.getData());
		Map<String, Object>map = new HashMap<String, Object>(2);
		List<CollectionForm> list=(List<CollectionForm>) result.get("deptNum");
		for(int i=0;i<list.size();i++) {
			collist= collectionFormService.getDataForDeptId(String.valueOf(list.get(i).getDeptId()));
			area=areaDeptService.getAreaName(list.get(i).getDeptId());//表ID  查询地区名
			colMap.put(list.get(i).getDeptId(),collist);
			areaMap.put(list.get(i).getDeptId(),area.getParentName());
		}
		if(!CollectionUtils.isEmpty(colMap)||!CollectionUtils.isEmpty(list)) {
			try {
				if(StringUtils.isEmpty(regionCode)) {
					area.setParentName("全部");
				}
				ExcelUtil.downloadDataforDeptId(response, colMap,area,list,areaMap);
			} catch (IOException e) {
				result2.setCode(RestServiceResult.CODE_UNKNOW);
				result2.setMsg("下载模板异常，请稍后再试！");
				ExceptionLogger.error("ContentController#getTemplate", "下载模板异常！ERROR:" + e.getMessage(), e);
				return result2;
			}
		}else {
			result2.setCode(RestServiceResult.CODE_UNKNOW);
			result2.setMsg("无数据下载！");
			ExceptionLogger.error("ContentController#getTemplate", "无数据下载！！ERROR:");
			return result2;
		}
		return result2;
	}
}
